package com.zsc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zsc.constant.MessageConstant;
import com.zsc.constant.StatusConstant;
import com.zsc.dto.DishPageQueryDTO;
import com.zsc.entity.Category;
import com.zsc.entity.Dish;
import com.zsc.entity.Setmeal;
import com.zsc.entity.SetmealDish;
import com.zsc.exception.DeletionNotAllowedException;
import com.zsc.exception.DishErroyException;
import com.zsc.exception.DishException;
import com.zsc.mapper.CategoryMapper;
import com.zsc.mapper.DishMapper;
import com.zsc.mapper.SetmealDishMapper;
import com.zsc.mapper.SetmealMapper;
import com.zsc.result.PageResult;
import com.zsc.service.CategoryService;
import com.zsc.service.DishService;
import com.zsc.utils.CopyUtil;
import com.zsc.vo.DishVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Stream;

/**
 * @author cjr165123050
 * @description 针对表【dish(菜品)】的数据库操作Service实现
 * @createDate 2024-05-19 11:14:01
 */
@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;

    /**
     * 分页查询菜品
     *
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {

        Page<Dish> dishPage = new Page<>(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());

        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();

        dishLambdaQueryWrapper.eq(!StringUtils.isBlank(dishPageQueryDTO.getName()),
                Dish::getName, dishPageQueryDTO.getName());
        dishLambdaQueryWrapper.eq(dishPageQueryDTO.getStatus() != null,
                Dish::getStatus, dishPageQueryDTO.getStatus());
        dishLambdaQueryWrapper.eq(dishPageQueryDTO.getCategoryId() != null,
                Dish::getCategoryId, dishPageQueryDTO.getCategoryId());

        Page<Dish> page = this.page(dishPage, dishLambdaQueryWrapper);

        List<Dish> records = page.getRecords();

        List<DishVO> dishVOS = new ArrayList<>();

        List<Category> list = categoryService.list();

        for (Dish record : records) {
            DishVO copy = CopyUtil.copy(record, DishVO.class);
            Optional<String> Categoryname = list.stream()
                    .filter(it -> record.getCategoryId().equals(it.getId()))
                    .map(Category::getName)
                    .findFirst();
            copy.setCategoryName(Categoryname.get());
            dishVOS.add(copy);
        }

        return new PageResult(page.getTotal(), dishVOS);
    }

    /**
     * 根据菜品分类id查询菜品
     *
     * @param categoryId
     * @return
     */
    @Override
    public List<Dish> listByCategoryId(long categoryId) {
        QueryWrapper<Dish> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("category_id", categoryId)
                .eq("status", StatusConstant.ENABLE)
                .orderByDesc("create_time");
        return this.list(queryWrapper);
    }

    @Override
    public DishVO getDishById(Long id) {
        DishVO dishVO = null;
        // 使用MyBatis Plus的BaseMapper提供的getById方法查询菜品数据
        Dish dish = this.getById(id);

        // 使用BeanUtils将Dish数据复制到DishVO对象中
        if (dish != null) {
            dishVO = CopyUtil.copy(dish, DishVO.class);
            Category category = categoryService.getById(dish.getCategoryId());
            dishVO.setCategoryName(category.getName());
        }
        return dishVO;
    }

    @Override
    @Transactional
    public void changeStatus(Integer status, Long dishId) {
        // 根据菜品id查询当前菜品所关联的套餐
        QueryWrapper<SetmealDish> setMealDishQueryWrapper = new QueryWrapper<>();
        setMealDishQueryWrapper.eq("dish_id", dishId);
        List<SetmealDish> setMealDishes = setmealDishMapper.selectList(setMealDishQueryWrapper);
        // 如果被引用的菜品位于启售中的套餐，并抛出异常
        for (SetmealDish setMealDish : setMealDishes) {
            QueryWrapper<Setmeal> setMealQueryWrapper = new QueryWrapper<>();
            setMealQueryWrapper.eq("id", setMealDish.getSetmealId());
            setMealQueryWrapper.eq("status", StatusConstant.ENABLE);
            Long count = setmealMapper.selectCount(setMealQueryWrapper);
            if (count > 0 && Objects.equals(status, StatusConstant.DISABLE)) {
                throw new DishException(MessageConstant.DISH_DISABLE_FAILED);
            }
        }
        Dish dish = new Dish();
        dish.setId(dishId);
        dish.setStatus(status);
        this.updateById(dish);
    }

    @Override
    @Transactional
    public void deleteBatch(List<Long> ids) {
        // 检查是否有菜品处于启售状态，如果有则抛出异常
        for (Long id : ids) {
            Dish dish = getById(id);
            if (dish.getStatus().equals(StatusConstant.ENABLE)) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }

        // 检查是否有菜品被套餐关联，如果有则抛出异常
        for (Long id : ids) {
            QueryWrapper<SetmealDish> wrapper = new QueryWrapper<>();
            wrapper.eq("dish_id", id);
            Long count = setmealDishMapper.selectCount(wrapper);
            if (count > 0) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
            }
        }

        // 执行删除操作
//        QueryWrapper<Dish> queryWrapper = new QueryWrapper<>();
//        queryWrapper.in("id", ids);
//        dishMapper.delete(queryWrapper);
        int deleteCount = dishMapper.deleteBatchIds(ids);
        if (deleteCount != ids.size()) {
            throw new DishErroyException("批量删除菜品失败");
        }
    }
}




